<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Chat{
		
	public function submitChat($chatText,$id_patient,$id_nutritionist,$isQuestion){
		$CI =& get_instance();
		
		
		$CI->db->query("
			INSERT INTO webchat (id_patient, id_nutritionist, text, isQuestion)
			VALUES (
				'".mysql_real_escape_string(htmlspecialchars($id_patient))."',
				'".mysql_real_escape_string(htmlspecialchars($id_nutritionist))."',
				'".mysql_real_escape_string(htmlspecialchars($chatText))."',
				'".mysql_real_escape_string(htmlspecialchars($isQuestion))."'
		)");
		
		// Returns the MySQLi object of the DB class
		$insertID =  $CI->db->insert_id();
		
		//Mesmo se der problema com o email, a mensagem vai ser enviada
		/*if($isQuestion){
			$config['protocol']='smtp';  
			$config['smtp_host']='ssl://smtp.googlemail.com';  
			$config['smtp_port']='465';  
			$config['smtp_timeout']='30';  
			$config['smtp_user']='chat@lianaguimaraes.com';  
			$config['smtp_pass']='folevilage';  
			$config['charset']='utf-8';  
			$config['newline']="\r\n";  
			
			$CI->load->library('email');
			$CI->email->initialize($config);
			
			$CI->load->model('Patient','p');
			$patient = $CI->p->get_patient_by_id($id_patient);
			$patient_name = $patient['name'];
			
			$CI->email->from('chat@lianaguimaraes.com','Chat');
			$CI->email->to('lianarcg@gmail.com');
			
			$CI->email->subject('Chat com '.$patient_name);
			$CI->email->message('http://lianaguimaraes.com/chat/'.$id_patient);
			if(!$CI->email->send()){
				/*return array(
					'status'	=> 0,
					'problem'	=> $CI->email->print_debugger()
				);
			}
		}*/
		
		return array(
			'status'	=> 1,
			'insertID'	=> $insertID
		);
	}
	
	public function getChats($lastID,$id_patient,$id_nutritionist){
		$CI =& get_instance();
		$limit	= 6;
		
		$lastID				= (int)$lastID;
		$id_patient			= (int)$id_patient;
		$id_nutritionist	= (int)$id_nutritionist;
		
		$query = $CI->db->query('SELECT count(id)as count FROM webchat WHERE id > '.$lastID.' AND id_patient = '.$id_patient.' AND id_nutritionist = '.$id_nutritionist);
		$numMsg = (int) $query->row()->count;

		$limit_query = '';
		if($numMsg>$limit){
			$inf = $numMsg - $limit;
			$limit_query = 'LIMIT '.$inf.','.$numMsg;
		}
		$query = $CI->db->query('SELECT * FROM webchat WHERE id > '.$lastID.' AND id_patient = '.$id_patient.' AND id_nutritionist = '.$id_nutritionist.' ORDER BY id ASC '.$limit_query);
	
		$chats = array();
		
		foreach ($query->result() as $chat){
			
			// Returning the GMT (UTC) time of the chat creation:	
			$chat->time = array(
				'hours'		=> gmdate('H',strtotime($chat->ts)),
				'minutes'	=> gmdate('i',strtotime($chat->ts))
			);
			
			$chat->gravatar = "";//Chat::gravatarFromHash($chat->gravatar);
			
			$chats[] = $chat;
			//sort($chats);
		}
	
		return array('chats' => $chats);
	}
	
}


?>